package com.javaee.service.doctor.impl;

import com.javaee.entity.Department;
import com.javaee.entity.Doctor;
import com.javaee.mapper.admin.DepartmentMapper;
import com.javaee.mapper.admin.DoctorMapper;
import com.javaee.mapper.doctor.UserDoctorMapper;
import com.javaee.service.doctor.AuthDoctorService;
import com.javaee.utils.AliOssUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;


@Service
public class AuthDoctorServiceImpl implements AuthDoctorService {
    @Autowired
    private UserDoctorMapper userDoctorMapper;
    @Autowired
    private DepartmentMapper departmentMapper;
    @Autowired
    private DoctorMapper doctorMapper;

    @Override
    public Doctor login(String phone, String password) {
        Doctor doctor = userDoctorMapper.findByPhone(phone);
        if (doctor != null && doctor.getPwd().equals(password)) {
            return doctor;
        }
        return null;
    }

    @Override
    public void registerDoctor(String password, String phone, String name, String job, String note, double fee, int dName, MultipartFile doctorPhoto) {
        Doctor doctor = new Doctor();
//        doctor.setUsername(username);
        doctor.setPwd(password);
        doctor.setPhone(phone);
        doctor.setName(name);
        doctor.setJob(job);
        doctor.setNote(note);
        doctor.setFee(fee);
        doctor.setDId(dName);
        // 上传头像到阿里云OSS
        String fileUrl = null;
        if (doctorPhoto != null && !doctorPhoto.isEmpty()) {
            try {
                // 尝试上传文件，并捕获可能抛出的异常
                fileUrl = AliOssUtil.uploadFile(doctorPhoto.getOriginalFilename(), doctorPhoto.getInputStream());
            } catch (Exception e) {
                // 记录异常信息，并决定如何处理异常
                e.printStackTrace();
                throw new RuntimeException("头像上传失败: " + e.getMessage());
            }
        }
        doctor.setTx(fileUrl);
        userDoctorMapper.insert(doctor);
    }

    @Override
    public List<Department> selectAllDepartments() {
        return doctorMapper.selectAllDepartments();
    }

    @Override
    public Doctor selectADoctor(int id) {
        return doctorMapper.selectADoctor(id);
    }

}